package com.sky.controller.admin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
public class LocalImageUploadController {

    private static final String UPLOAD_DIR = "D:\\tu";
    private static final long MAX_FILE_SIZE = 100 * 1024 * 1024; // 100MB

    @PostMapping("/admin/common/upload")
    public String uploadImage(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "上传失败，请选择图片";
        }

        // 检查文件大小
        if (file.getSize() > MAX_FILE_SIZE) {
            return "上传失败，图片大小不能超过 100MB";
        }

        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFileName = UUID.randomUUID().toString() + fileExtension;

        File dest = new File(UPLOAD_DIR + File.separator + newFileName);

        try {
            // 创建目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            // 保存文件
            file.transferTo(dest);
            return "上传成功，文件路径：" + dest.getAbsolutePath();
        } catch (IOException e) {
            e.printStackTrace();
            return "上传失败：" + e.getMessage();
        }
    }
}